<?php
/**
 * Created by PhpStorm.
 * User: houyuesong
 * Date: 2020/4/8
 * Time: 18:26
 * Desc: 权限基类
 */
declare (strict_types=1);

namespace app\backend\base\controller;

use app\BaseController;
use app\extend\model\Auth;
use app\extend\model\Menu;
use app\extend\model\OperateLog;
use think\facade\Cache;

class Base extends BaseController
{
    public function initialize()
    {
        $this->_auth();
    }

    /**
     * 权限
     */
    private function _auth()
    {
        //判断是否登录
        if (empty(session('uid')) || empty(session('nickname')) || empty(session('role_id'))) {
                if (request()->isAjax()) {
                exit(json_encode(_E('登录过期,请重新登录再继续操作', [
                    'url' => (string)url('Login/index')
                ], 500001)));
            } else {
                header('Location:' . url('Login/index'));
                exit();
            }
        }

        //判断权限
        $module = 'backend';
        $controller = request()->controller();
        $action = request()->action();

        //过滤
        $filterAuthList = [
            'Index/index',//首页框架
            'Index/theme',//主题模板
            'Index/lock',//锁屏
            'Index/getWithdrawCount',//提现数量
            'Index/getRechargeCount',//充值数量
            'Index/getOrderCount',//订单数量
            'Tool/upload',//上传
        ];

        if (in_array($controller . '/' . $action, $filterAuthList)) {
            return true;
        }

        $menuInfo = Menu::where([
            ['m', '=', $module],
            ['c', '=', $controller],
            ['a', '=', $action]
        ])->field('id,type,parent_id,name')->find();

        if(empty($menuInfo)){
            exit(json_encode(_E('暂无权限,请联系管理员', 500002)));
        }

        $authId = Auth::where([
            ['role_id', '=', session('role_id')],
            ['menu_id', '=', $menuInfo->id],
        ])->value('id');

        if (empty($authId)) {
            if ($menuInfo->type == 1) {//按钮显示错误
                exit(json_encode(_E('暂无权限,请联系管理员', 500002)));
            } else {//菜单显示页面
                header('location:' . url('Exception/notAuth'));
                exit();
            }
        }

        //记录模块名字和方法
        $cName = '';
        if ($menuInfo->parent_id > 0) {
            $cName = Menu::where([
                ['id', '=', $menuInfo->parent_id],
            ])->value('name');
        }

        //添加到操作日志表
        OperateLog::insert(
            [
                'admin_id' => session('uid'),
                'nickname' => session('nickname'),
                'c' => empty($cName) ? $menuInfo->name : $cName,
                'a' => empty($cName) ? '' : $menuInfo->name,
                'url' => $module . '/' . $controller . '/' . $action,
                'ip' => getClientIp(),
                'browser' => getUserBrowser(),
                'ext' => empty(input()) ? '' : json_encode(input()),
                'created_at' => date('Y-m-d H:i:s'),
            ]
        );
    }
}
